package com.smartfast4j.manager.modules.sys.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.smartfast4j.common.Constants;
import com.smartfast4j.common.annotation.LogRecord;
import com.smartfast4j.common.annotation.PermissionLimit;
import com.smartfast4j.common.bean.R;
import com.smartfast4j.common.component.cache.annotation.Cache;
import com.smartfast4j.common.component.cache.annotation.CacheClear;
import com.smartfast4j.common.config.Cachekey;
import com.smartfast4j.common.util.ConversionUtil;
import com.smartfast4j.manager.common.bean.LoginUserInfo;
import com.smartfast4j.manager.common.bean.ZtreeMenuVo;
import com.smartfast4j.manager.common.controller.ManagerBaseController;
import com.smartfast4j.manager.modules.sys.bean.SysMenu;
import com.smartfast4j.manager.modules.sys.service.SysResourceService;
import com.smartfast4j.pojo.sys.SysResource;
import com.smartfast4j.pojo.sys.SysResourceExample;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* SysResourceController
*  由代码生成器生成
*/
@PermissionLimit //在类上标注了@PermissionLimit注解后这个类下的所有接口都需要做访问权限控制
@RestController
@RequestMapping("/sysResource")
public class SysResourceController extends ManagerBaseController {

    @Autowired
    private SysResourceService sysResourceService;

    @LogRecord(operation = "新增资源",remark = "新增系统资源",moduleName = "资源管理")
    @RequestMapping(value = "/add")
    public R add(SysResource sysResource){
        if(ConversionUtil.isEmptyParameter(sysResource.getLevel())){
            sysResource.setLevel(1);
        }
        sysResource.setCreateUser(getLoginUserId());
        sysResource.setUpdateUser(getLoginUserId());
        sysResourceService.add(sysResource);
        return R.ok();
    }

    @CacheClear(key = "'" + Cachekey.Sys.RESOURCE+ "' + #sysResource.id") //更新完成后清除缓存
    @LogRecord(operation = "修改资源",remark = "修改系统资源",moduleName = "资源管理")
    @RequestMapping(value = "/update")
    public R update(SysResource sysResource){
        if(ConversionUtil.isEmptyParameter(sysResource.getLevel())){
            sysResource.setLevel(1);
        }
        sysResource.setUpdateUser(getLoginUserId());
        sysResourceService.updateByPrimaryKeySelective(sysResource);
        return R.ok();
    }

    /**
     * 根据资源id批量清除资源权限标识
     * @param ids 资源ID，以逗号分隔
     * @return
     */
    @LogRecord(operation = "清除权限",remark = "根据资源id清除资源权限标识",moduleName = "资源管理")
    @RequestMapping(value = "/clearPerm")
    public R clearPerm(String ids){
        List<Long> idList = new ArrayList<>();
        if(StringUtils.isNotEmpty(ids)){
            String[] idArr = ids.split(",");
            for(String id:idArr){
                idList.add(Long.parseLong(id));
            }
        }
        //根据资源id删除
        sysResourceService.clearPerm(getLoginUserId(), idList);
        return R.ok();
    }

    /**
     * 根据资源id批量删除资源
     * @param ids 要删除的资源ID，以逗号分隔
     * @return
     */
    @LogRecord(operation = "删除资源",remark = "根据资源id删除资源",moduleName = "资源管理")
    @RequestMapping(value = "/delete")
    public R delete(String ids){
        List<Long> idList = new ArrayList<>();
        if(StringUtils.isNotEmpty(ids)){
            String[] idArr = ids.split(",");
            for(String id:idArr){
                idList.add(Long.parseLong(id));
            }
        }
        //根据资源id删除
        sysResourceService.delete(getLoginUserId(), idList);
        return R.ok();
    }
    /**
     * 根据资源ID获取资源信息
     * @param id
     * @return
     */
    @Cache(key = "'"+Cachekey.Sys.RESOURCE+"'+#id") //缓存
    @GetMapping(value = "/info/{id}")
    public R info(@PathVariable("id") Long id) {
        return R.ok(sysResourceService.selectByPrimaryKey(id));
    }

    /**
     * 分页查询系统资源
     * @param offset 从第几条开始取
     * @param limit 每次取多少条
     * @param name 资源名称
     * @return
     */
    @RequestMapping(value = "/list")
    public R list(Integer offset, Integer limit,String name,Long id){
        if (offset != null && limit != null) {
            //分页查询
            PageHelper.offsetPage(offset, limit);
        }
        SysResourceExample resourceExample = new SysResourceExample();
        SysResourceExample.Criteria criteria = resourceExample.createCriteria();
        criteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG.NO);
        if(StringUtils.isNotEmpty(name)){
            criteria.andNameLike("%"+name+"%");
            //把该name下的子资源一起查询出来
            resourceExample.or().andParentNamesLike("%" + name + "%").andDeleteFlagEqualTo(Constants.DELETE_FLAG.NO);
        }
        if(id != null){
            criteria.andIdEqualTo(id);
            //把该Id下的子资源一起查询出来
            resourceExample.or().andParentIdsLike("%"+id+"%").andDeleteFlagEqualTo(Constants.DELETE_FLAG.NO);
        }
        resourceExample.setOrderByClause("create_time desc, update_time desc");
        List<SysResource> sysResourceList = sysResourceService.selectByExample(resourceExample);
        //分页信息
        PageInfo<SysResource> pageInfo = new PageInfo(sysResourceList);
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("total",pageInfo.getTotal());
        dataMap.put("rows", pageInfo.getList());
        //服务端分页，返回的结果必须包含total、rows两个参数。漏写或错写都会导致表格无法显示数据。
        return R.ok(dataMap);
    }

    /**
     * 根据资源ID获取资源信息以及子资源信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/getResourceTreeById")
    public R getResourceTreeById(Long id) {
        return R.ok(sysResourceService.getResourceTreeById(id));
    }

    /**
     * 根据资源ID获取资源信息以及子资源信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/getResourceTreeById2")
    public R getResourceTreeById2(Long id) {
        return R.ok(sysResourceService.getResourceTreeById2(id));
    }

    /**
     * 获取资源树列表
     * @return
     */
    @RequestMapping(value = "/getResourceTreeList")
    public R getResourceTreeList() {
        return R.ok(sysResourceService.getResourceTreeList());
    }

    /**
     * 获取导航菜单
     * @return
     */
    @RequestMapping("/navMenu")
    public R getNavMenu(){
        LoginUserInfo loginUserInfo = getCurrLoginUser();
        List<SysMenu> sysMenuList = sysResourceService.getNavMenu(loginUserInfo.getId());
        return R.ok(sysMenuList);
    }

    /**
     * 获取Ztree菜单列表
     * @return
     */
    @PostMapping("/treeList")
    public R treeList(Integer menuType) {
        List<ZtreeMenuVo> menuVoList = sysResourceService.getZtreeMenu(getLoginUserId(),menuType);
        return R.ok(menuVoList);
    }

    /**
     * 根据角色ID获取Ztree菜单列表
     * @return
     */
    @RequestMapping("/checkTreeList")
    public R checkTreeList(Long roleId) {
        List<ZtreeMenuVo> menuVoList = sysResourceService.getCheckTreeList(getLoginUserId(),roleId);
        return R.ok(menuVoList);
    }
}
